<template>
  <div class="post-detail-container">
    <div class="author-section">
      <div class="author-info">
        <img :src="post.authorAvatar" alt="author avatar" class="author-avatar" />
        <h3>{{ post.author }}</h3>
        <p class="author-bio">{{ post.authorBio }}</p>
      </div>
      <div class="other-topics">
        <h4>该作者的其他话题</h4>
        <div
            class="topic-item"
            v-for="topic in authorTopics"
            :key="topic.id"
            @click="goToTopicDetail(topic.id)"
        >
          <h5>{{ topic.title }}</h5>
          <p>{{ topic.description.slice(0, 50) }}...</p>
        </div>
      </div>
    </div>

    <div class="post-content-section">
      <div class="post-content-wrapper">
        <div class="post-header">
          <div class="post-author">
            <img :src="post.authorAvatar" alt="author avatar" class="post-author-avatar" />
            <div class="post-author-info">
              <span class="author-name">{{ post.author }}</span>
              <span class="post-time">{{ formatTime(post.timeAgo) }}</span>
            </div>
          </div>
          <h1 class="post-title">{{ post.title }}</h1>
        </div>
        <div class="post-content">
          <p>{{ post.description }}</p>
          <img
              v-if="post.image"
              :src="post.image"
              alt="post image"
              class="post-image"
              @load="handleImageLoad"
          />
          <video v-if="post.video" controls class="post-video">
            <source :src="post.video" type="video/mp4" />
            您的浏览器不支持视频标签。
          </video>
        </div>

        <div class="action-buttons">
          <button class="action-btn" @click="likePost">
            <i :class="['far', 'fa-thumbs-up', { 'fas': post.isLiked }]"></i>
            <span>{{ post.likes }}</span>
          </button>
          <button class="action-btn" @click="toggleFavorite">
            <i :class="['far', 'fa-heart', { 'fas': post.isFavorite }]"></i>
            <span>{{ post.isFavorite ? '已收藏' : '收藏' }}</span>
          </button>
          <button class="action-btn" @click="showComments = !showComments">
            <i class="far fa-comment"></i>
            <span>{{ post.commentCount }}</span>
          </button>
        </div>

        <div class="comments-section" v-if="showComments">
          <h4>评论</h4>
          <div class="comment-list">
            <div
                class="comment-item"
                v-for="comment in post.comments"
                :key="comment.id"
            >
              <img :src="comment.avatar" alt="comment author avatar" class="comment-avatar" />
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-author">{{ comment.author }}</span>
                  <span class="comment-time">{{ formatTime(comment.timeAgo) }}</span>
                </div>
                <p class="comment-text">{{ comment.text }}</p>
              </div>
            </div>
          </div>
          <div class="comment-form">
            <el-input
                v-model="newComment"
                type="textarea"
                :rows="3"
                placeholder="添加评论..."
            />
            <el-button type="primary" @click="addComment">提交评论</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { ElMessage } from 'element-plus'

const counterStore = useCounterStore()
const route = useRoute()
const router = useRouter()

const post = ref({
  id: 0,
  title: '',
  author: '',
  authorAvatar: '',
  authorBio: '',
  timeAgo: '',
  description: '',
  image: null,
  video: null,
  likes: 0,
  isLiked: false,
  commentCount: 0,
  isFavorite: false,
  comments: [] as Comment[]
})

const authorTopics = ref([] as Topic[])
const newComment = ref('')
const showComments = ref(true)
const isLoading = ref(false)

onMounted(async () => {
  const postId = Number(route.params.id)
  if (isNaN(postId)) {
    ElMessage.error('无效的话题ID')
    router.push({ name: 'Community' })
    return
  }

  try {
    isLoading.value = true
    post.value = await counterStore.getPostById(postId)
    authorTopics.value = await counterStore.getTopicsByAuthor(post.value.author)
  } catch (error) {
    ElMessage.error('加载话题数据失败')
    console.error(error)
  } finally {
    isLoading.value = false
  }
})

const formatTime = (timeAgo: string) => {
  // 这里可以添加更复杂的时间格式化逻辑
  return timeAgo
}

const goToTopicDetail = (id: number) => {
  router.push({ name: 'PostDetail', params: { id } })
}

const likePost = async () => {
  try {
    const updatedPost = await counterStore.likePost(post.value.id)
    post.value.likes = updatedPost.likes
    post.value.isLiked = updatedPost.isLiked
    ElMessage.success(post.value.isLiked ? '点赞成功' : '已取消点赞')
  } catch (error) {
    ElMessage.error('操作失败')
    console.error(error)
  }
}

const toggleFavorite = async () => {
  try {
    const updatedPost = await counterStore.toggleFavorite(post.value.id)
    post.value.isFavorite = updatedPost.isFavorite
    ElMessage.success(post.value.isFavorite ? '已收藏' : '已取消收藏')
  } catch (error) {
    ElMessage.error('操作失败')
    console.error(error)
  }
}

const addComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    const comment = await counterStore.addComment(post.value.id, newComment.value)
    post.value.comments.unshift(comment)
    post.value.commentCount += 1
    newComment.value = ''
    ElMessage.success('评论发布成功')
  } catch (error) {
    ElMessage.error('评论发布失败')
    console.error(error)
  }
}

const handleImageLoad = () => {
  // 图片加载完成后可以执行的操作
}
</script>

<style scoped>
.post-detail-container {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  gap: 20px;
  min-height: 100vh;
}

.author-section {
  width: 25%;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.author-info {
  text-align: center;
}

.author-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.author-bio {
  font-size: 0.9em;
  color: #666;
}

.other-topics {
  margin-top: 20px;
}

.topic-item {
  margin-bottom: 15px;
  cursor: pointer;
  padding: 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.topic-item:hover {
  background-color: #f0f0f0;
}

.topic-item h5 {
  margin: 0 0 5px;
  font-size: 1em;
}

.topic-item p {
  margin: 0;
  font-size: 0.9em;
  color: #666;
}

.post-content-section {
  width: 75%;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.post-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-header {
  margin-bottom: 10px;
}

.post-author {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.post-author-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.post-author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: bold;
}

.post-time {
  font-size: 0.9em;
  color: #666;
}

.post-title {
  margin: 0 0 10px;
  font-size: 1.5em;
}

.post-content {
  margin: 20px 0;
  line-height: 1.6;
}

.post-image {
  max-width: 100%;
  margin-top: 10px;
  border-radius: 8px;
  max-height: 500px;
  object-fit: contain;
}

.post-video {
  max-width: 100%;
  margin-top: 10px;
  border-radius: 8px;
  max-height: 500px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  padding: 10px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  margin: 10px 0;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.2s;
}

.action-btn:hover {
  background-color: #f5f5f5;
  color: #42b983;
}

.action-btn i {
  font-size: 16px;
}

.action-btn i.fas {
  color: #42b983;
}

.comments-section {
  margin-top: 20px;
}

.comment-list {
  margin-top: 10px;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.comment-author {
  font-weight: bold;
}

.comment-time {
  font-size: 0.8em;
  color: #666;
}

.comment-text {
  margin: 0;
  font-size: 0.9em;
  line-height: 1.5;
}

.comment-form {
  margin-top: 20px;
}

.comment-form textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: vertical;
  min-height: 100px;
}

.comment-form button {
  margin-top: 10px;
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>